package com.google.code.p.odbcconnectionchecker;

import java.awt.Image;
import java.awt.TrayIcon;
import java.beans.XMLDecoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import javax.swing.ImageIcon;

public class ConnectionCheckerTrayIcon {

	private ConnectionCheckerPopupMenu popupMenu;
	private static TrayIcon trayIcon;

	/**
	 * Create the Connection Checker tray Icon, using the default image 
	 * and loading any pre-existing popupMenu through serialization or 
	 * creating a new instance of it 
	 */
	public ConnectionCheckerTrayIcon() {
		
		trayIcon = new TrayIcon(getTrayIconImage());
		trayIcon.setImageAutoSize(true);
		
		popupMenu = loadPopupMenu();
		trayIcon.setPopupMenu(popupMenu);
		
	}
	
	/**
	 * Shows a message using the TrayIcon.
	 * @param caption A String representing the title of the message
	 * @param message A String representing the text of the message
	 * @param messageType A TrayIcon.MessageType defining the type of message
	 */
	public static void displayMessage(String caption, String message, TrayIcon.MessageType messageType) { 
		trayIcon.displayMessage(caption, message, messageType);
	}
	
	/*
	 * Load the default image for the tray icon 
	 */
	private static Image getTrayIconImage() { 
		URL imageURL = ConnectionCheckerTrayIcon.class.getResource("cmdb-hi.png");
		return (new ImageIcon(imageURL)).getImage();
	}
	
	/*
	 * Load, if existing, the serialized instance of the popupMenu
	 */
	private ConnectionCheckerPopupMenu loadPopupMenu() {
		ConnectionCheckerPopupMenu popupMenu;
		try {
			XMLDecoder decoder = new XMLDecoder(new FileInputStream(ConnectionChecker.getJarPath() + "popupMenu.xml"));
			popupMenu = (ConnectionCheckerPopupMenu) decoder.readObject();
			return popupMenu;
		} catch (FileNotFoundException e) {
			popupMenu = new ConnectionCheckerPopupMenu();
			return popupMenu;
		}
	}
	
	/*
	 * Returns the system tray object
	 * @return An instance of the tray icon
	 */
	protected static TrayIcon getTrayIcon() {
		return trayIcon;
	}
}
